<template>
  <div>
    <el-popover :title="title" v-if="content && content.length > limit" placement="top-start" width="400" trigger="hover">
      <div v-if="type === 'string'">
        {{ content }}
        <div style="text-align: right; margin: 0">
          <el-button class="copyParams" data-clipboard-text type="text" size="mini" @click="copy">复制 </el-button>
        </div>
      </div>
      <div v-if="type === 'form'">
        <el-form label-width="120px" :inline="true">
          <el-form-item :label="item" v-for="(item, index) in Object.keys(JSON.parse(content))" :key="index">
            <el-input v-model="JSON.parse(content)[item]" readonly></el-input>
          </el-form-item>
        </el-form>
      </div>

      <span slot="reference">{{ contentFilter }}</span>
    </el-popover>

    <div v-else>
      {{ content }}
    </div>
  </div>
</template>

<script>
import Clipboard from 'clipboard';
export default {
  props: {
    content: {
      required: false,
      type: String | Object,
    },
    limit: {
      default: 10,
      type: [Number, String],
    },
    title: {
      default: '',
      type: String,
    },
    type: {
      default: 'string',
      type: String,
    },
  },
  computed: {
    contentFilter() {
      if (!this.content) {
        return false;
      }

      if (this.content.length > this.limit) {
        return this.content.substring(0, this.limit) + '...';
      } else {
        return this.content;
      }
    },
  },
  methods: {
    copy() {
      // 模拟 输入框
      var cInput = document.createElement('input');
      cInput.value = this.content;
      document.body.appendChild(cInput);
      cInput.select(); // 选取文本框内容

      // 执行浏览器复制命令
      // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签）
      // Input要在正常的编辑状态下原生复制方法才会生效

      document.execCommand('copy');

      this.$message({
        type: 'success',
        message: '复制成功',
      });
      // 复制成功后再将构造的标签 移除
      document.body.removeChild(cInput);

      //触发器
      // try {
      //     navigator.clipboard.writeText(this.content).then(res => {
      //         this.$message.success("复制成功")
      //     });
      // } catch (error) {
      //     this.$message.error("复制失败请手动复制")
      // }
    },
  },
};
</script>

<style lang="scss" scoped></style>
